package com.bj.zspace.cat.controller;

import com.dianping.cat.Cat;
import com.dianping.cat.message.ForkedTransaction;
import com.dianping.cat.message.Transaction;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:liuwenqing
 * @Date:2024/12/4 19:26
 * @Description:
 **/
@RestController
public class ForkedTransactionTest {
    /**
     * 简单的创建fork, 查看原理效果
     */
    @GetMapping(value = "fork1")
    public String testFork1() {

        ForkedTransaction ft = Cat.newForkedTransaction("fork1", "fork1_name");
        Transaction transaction = Cat.newTransaction("fork1_t", "fork1_t_name");
        transaction.setStatus("0");
        transaction.complete();
        ft.setStatus("0");
        ft.complete();
        return "ok";
    }

    /**
     * 创建ForkTransaction之后：执行fork
     */
    @GetMapping(value = "fork2")
    public String testFork2() {

        ForkedTransaction ft = Cat.newForkedTransaction("fork2", "fork2_name");
        // fork操作 会把当前的ForkTransaction放入到当前MessageTree并加入到Stack中，执行真实的记录
        ft.fork();
        ft.setStatus("0");
        ft.complete();
        return "ok";
    }

    @GetMapping("fork3")
    public String testFork3() {
        Transaction transaction = Cat.newTransaction("t_fork3", "t_fork3_name");
        ForkedTransaction forkedTransaction = Cat.newForkedTransaction("fork3", "fork3_name");
        new ForkThread(forkedTransaction, 1000).start();
        ForkedTransaction forkedTransaction1 = Cat.newForkedTransaction("fork3_1", "fork3_1_name");
        new ForkThread(forkedTransaction1, 1000).start();
        transaction.setStatus("0");
        transaction.complete();
        return "ok";
    }


    class ForkThread extends Thread {

        private ForkedTransaction ft;
        private long sleep;

        public ForkThread(ForkedTransaction ft, long sleep) {
            this.ft = ft;
            this.sleep = sleep;
        }

        @Override
        public void run() {
            try {
                ft.fork();
                Thread.sleep(sleep);
            } catch (Exception e) {
                ft.setStatus(e);
            } finally {
                ft.complete();
            }

        }
    }

}
